package adminService

import (
	"fmt"
	"news_for_deepseek_interface/model"
	adminModel "news_for_deepseek_interface/model/admin"
	"news_for_deepseek_interface/utils"
	"strconv"
	"strings"
)

func GetUserRoles(adminId int) (node []map[string]interface{}, err error) {

	db := model.GetInstance().GetDB()

	var AdminGroupIds []int
	if err = db.Model(&adminModel.AdminWithGroupStruct{}).Where("admin_id = ?", adminId).Pluck("admin_group_id", &AdminGroupIds).Error; err != nil {
		err = fmt.Errorf("查询关联分组失败：%v", err)
		return
	}
	// 查询分组对应的权限
	var roleIds []string
	if err = db.Model(&adminModel.AdminGroupStruct{}).Where("id in (?)", AdminGroupIds).Pluck("rules", &roleIds).Error; err != nil {
		err = fmt.Errorf("查询权限分组失败：%v", err)
		return
	}

	//查询菜单列表
	dbRule := db
	// 查询菜单列表
	var adminAuthRuleData []adminModel.AdminAuthRuleStruct
	if !utils.IsStringInSlice("*", roleIds) {
		roleIdStr := ""
		for _, v := range roleIds {
			if v != "*" {
				roleIdStr += v + ","
			}
		}
		dbRule = dbRule.Model(&adminModel.AdminAuthRuleStruct{}).
			Where("id in (?)", strings.Split(roleIdStr, ","))
	}

	if err = dbRule.Find(&adminAuthRuleData).Error; err != nil {
		err = fmt.Errorf("查询菜单列表失败：%v", err)
		return
	}

	//拼装返回菜单
	node = make([]map[string]interface{}, 0)
	for _, item := range adminAuthRuleData {
		if item.Level == 0 {
			rootNode := buildNode(adminId, item, adminAuthRuleData)
			node = append(node, rootNode)
		}
	}

	return
}

// 定义一个方法，用于构建节点及其子节点的数据结构
func buildNode(adminId int, item adminModel.AdminAuthRuleStruct, sortedData []adminModel.AdminAuthRuleStruct) map[string]interface{} {
	node := make(map[string]interface{})
	for _, subItem := range sortedData {
		if subItem.ParentId == item.Id {
			// 递归调用 buildNode 方法构建子节点
			childNode := buildNode(adminId, subItem, sortedData)
			if len(childNode) > 0 {
				// 将子节点加入当前节点的 "children" 字段中
				if _, ok := node["children"]; !ok {
					node["children"] = make([]map[string]interface{}, 0)
				}
				node["children"] = append(node["children"].([]map[string]interface{}), childNode)
			}
		}
	}
	// 添加当前节点的其他字段
	node["path"] = item.Path
	node["rank"] = item.Rank
	if item.Name != "" {
		node["name"] = item.Name
		node["query"] = ""

		//url额外处理
		if item.Handle == 1 {
			node["name"] = item.Name + "/?channel_id=" + strconv.Itoa(adminId)
		}
	}
	if item.Component != "" {
		node["component"] = item.Component
	}
	meta := make(map[string]interface{})
	meta["showLink"] = item.ShowLink == 1
	meta["showParent"] = item.ShowParent == 1
	meta["title"] = item.Title
	meta["icon"] = item.Icon

	node["meta"] = meta

	return node
}
